<?php
/**
*   Yz_Object adds to the Yz_Class functionality the usage of getter/setter methods
*
*
*/

abstract class Yz_Object
    extends Yz_Class
{

    /*******************************
    ****   ArrayAccess methods   ***
    *******************************/

    /** test if a key/index/property exists in the object
     *      By default, it means the existence of method "get$var()",
     *      or the result of <code>_has_($var)</code>
     *  @param scalar $var
     *  @return bool
     *  @throw TypeMismatch if $var is not a scalar
     */
    public function offsetExists( $var )
    {
        $var = $this->adjustIndex( $var );
        $method = $this->findAccessor($var, 'get');
        if ( false !== $method )
            return true;
        return $this->_has_( $var );
    }

    /** try to get a key/index/property
     *      By default, it calls the method <code>get$var()</code> if it exists,
     *      or <code>_get_($var)</code>
     *  @param scalar $var
     *  @return mixed|null if index not in list
     *  @throw TypeMismatch if $var is not a scalar
     */
    public function offsetGet( $var )
    {
        $var = $this->adjustIndex( $var );
        $method = $this->findAccessor($var, 'get');
        if ( false !== $method )
            return $this->$method();
        return $this->_get_( $var );
    }

    /** try to set a key/index/property
     *      By default, it calls the method <code>set$var($value)</code> if it exists,
     *      or <code>_set_($var, $value)</code>
     *  @param scalar $var
     *  @param mixed $value
     *  @return chainable - mostly ignored
     *  @throw TypeMismatch if $var is not a scalar
     */
    public function offsetSet( $var, $value )
    {
        $var = $this->adjustIndex( $var );
        $method = $this->findAccessor($var, 'set');
        if ( false !== $method )
            return $this->$method( $value );
        return $this->_set_( $var, $value );
    }

    /** try to `unset'' a key/index/property
     *      By default, it calls the method <code>unset$var()</code> if it exists,
     *      or <code>_del_($var, $value)</code>
     *  @param scalar $var
     *  @return chainable - mostly ignored
     *  @throw TypeMismatch if $var is not a scalar
     */
    public function offsetUnset( $var )
    {
        $var = $this->adjustIndex( $var );
        $method = $this->findAccessor($var, 'unset');
        if ( false !== $method )
            return $this->$method();
        return $this->_del_( $var );
    }


    /***********************
     *   Protected methods
     **********************/

    /** test if a getter for the index exists
     *   @param string index
     *   @return string|false
     */
    protected function findAccessor( $index, $accessType )
    {
        $method = $accessType . $index;
        return method_exists( $this, $method ) ? $method : false;
    }

} // class

